
package com.probiz.estore.imports.handler.product;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.probiz.estore.common.model.product.Brand;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.model.product.ProductTypeBrand;
import com.probiz.estore.imports.handler.ColumnHandler;
import com.probiz.estore.imports.handler.basic.ColumnBasicHandler;
import com.probiz.estore.imports.model.Column;
import com.probiz.estore.imports.model.ImportModel;
import com.probiz.estore.product.service.BrandManager;

public class BrandHandler extends ColumnBasicHandler implements ColumnHandler {
	private Logger logger = Logger.getLogger(BrandHandler.class);
	private BrandManager brandManager;
	public void setBrandManager(BrandManager brandManager) {
		this.brandManager = brandManager;
	}

	public void setProperty(ImportModel importModel, Column column) throws Exception {
		Product product = (Product) importModel.getTarget();
		String value = column.getValue();
		if(StringUtils.isBlank(value)){
			return;
		}
		List<Brand> brandList = brandManager.listByProperty("brandName", value);
		if(0 == brandList.size()){
			//设置结果
			importModel.setResult(ImportModel.RESULT_ERROR);
			String msg = "无法导入，因为找不到品牌名称为【"+value+"】的品牌";
			logger.error(msg);
			importModel.setMsg(msg);
			return;
		}else if(1== brandList.size()){
			Brand brand = brandList.get(0);
			//必须是这个商品的商品类型所关联的品牌才生效
			boolean flag = false;
			for(ProductTypeBrand productTypeBrand : product.getProductType().getProductTypeBrands()){
				if(productTypeBrand.getBrand().getBrandId().equals(brand.getBrandId())){
					flag = true;
					break;
				}
			}
			if(flag){
				product.setBrand(brand);
			}else{
				//设置结果
				importModel.setResult(ImportModel.RESULT_ERROR);
				String msg = "无法导入，因为该品牌【"+value+"】不是商品的商品类型【"+product.getProductType().getProductTypeName()+"】的关联品牌中的其中一个";
				logger.error(msg);
				importModel.setMsg(msg);
				return;
			}
		}else{
			//设置结果
			importModel.setResult(ImportModel.RESULT_ERROR);
			String msg = "无法导入，因为找到多个品牌名称均为【"+value+"】的品牌，系统无法确定唯一";
			logger.error(msg);
			importModel.setMsg(msg);
			return;
		}
	}


}
